AsgDetalleVenta = function(){
	var rowBodyTpl = Ext.create("Ext.XTemplate", [
      "<tpl for=\".\">",
      	"<div class=\"row\">",
      		"<div class=\"tplTr\">",
      			"<div class=\"tplTd\">",
      				"{asgVentaAsunto}{asgSeguimientoDescripcion}",
  				"</div>",
			"</div>",
		"</div>",
		"</div>",
	   "</tpl>"
	]);
	return {
		rendererEstado: function(value){
			var tooltip = "";
			if(value == "1"){
				value = "bullet_green.png";
				tooltip = "VENTA FINALIZADO";
			}else {
				value = "bullet_red.png";
				tooltip = "VENTA EN PROCESO";
			}
			return "<img src=\"" + Asg.constants.CONTEXT_PATH + "/resources/images/" + value + "\" data-qtip=\"" + tooltip + "\" />";
		},
		finalizar: function(btn){
			if(btn == "no") return;
			var asgVenta = Asg.Grid.getSelectedRow("asgDetalleVentasGrid");
			Asg.Message.progress("Guardarndo Informaci\u00F3n...");
			Ext.Ajax.request({
				timeout: Asg.constants.TIMEOUT_SECONDS,
				url: Asg.constants.CONTEXT_PATH + "/ventas/finalizar",
				params: {
					asgVentaId: asgVenta.get("asgVentaId"),
					asgPolizaId: AsgSeguros.getAsgPolizaId()
				},
				callback: function(options, success, response){
					Ext.Msg.hide();
					var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
					if(!success || !jsonObject){
						Asg.Message.alertInvalid(Asg.constants.DEFAULT_ERROR_MESSAGE);
						return
					}
					Asg.Message.alert(jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE);
					if(jsonObject.success){
						var grid = Ext.getCmp("asgDetalleVentasGrid");
						var asgDetalleVentaStore = grid.getStore();
						asgDetalleVentaStore.currentPage = 1;
 	        		    asgDetalleVentaStore.load({params:{restart: true}});
						Asg.Grid.loadData("asgDetalleSeguimientosGrid", []);
						Asg.Grid.loadData("asgDetalleContactosGrid", []);
						return;
					}
				}
			});
		},
		confirmFinalizacion: function(){
			var asgVenta = Asg.Grid.getSelectedRow("asgDetalleVentasGrid");
			if(asgVenta == null || asgVenta.length == 0){
				Asg.Message.alertInvalid("Debe seleccionar el venta a finalizar");
				return;
			}
			Asg.Message.confirm("\u00BFEst\u00E1 seguro que desea finalizar el venta?", AsgDetalleVenta.finalizar);
		},
		saveVenta: function(ctgTipoSeguro){
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			Ext.getCmp(ctgTipoSeguro == 1 ? "asgVentaForm" : "asgVentaJuridicaForm").getForm().submit({
    			url: Asg.constants.CONTEXT_PATH + "/ventas/save",
    			timeout: Asg.constants.TIMEOUT_SECONDS,
    			params: {"asgVenta.asgPoliza.asgPolizaId": AsgSeguros.getAsgPolizaId()},
    			success: function(form, action){
    				Asg.Message.alert(action.result.message);
					if(action.result.success){
						Asg.Utils.setValue("asgEstados", "0");
						var grid = Ext.getCmp("asgDetalleVentasGrid");
						var asgDetalleVentaStore = grid.getStore();
						asgDetalleVentaStore.currentPage = 1;
 	        		    asgDetalleVentaStore.load({params:{restart: true}});
						Asg.Grid.loadData("asgDetalleSeguimientosGrid", []);
						Asg.Grid.loadData("asgDetalleContactosGrid", []);
		    			Ext.WindowMgr.get(ctgTipoSeguro == 1 ? "asgVentaWindow" : 
		    				"asgVentaJuridicaWindow").hide();
					}
    			},
    			failure: Asg.Form.failureProcedure
   			});
		},
		saveSeguimiento: function(){
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			Ext.getCmp("asgSeguimientoForm").getForm().submit({
    			url: Asg.constants.CONTEXT_PATH + "/seguimientos/save",
    			timeout: Asg.constants.TIMEOUT_SECONDS,
    			params: {
    				"asgSeguimiento.asgVenta.asgVentaId": AsgSeguros.getAsgVentaId(),
    				"identifier": AsgSeguros.getAsgVentaId(),
    				type: "venta"
				},
    			success: function(form, action){
    				Asg.Message.alert(action.result.message);
					if(action.result.success){
						Asg.Grid.loadData("asgDetalleSeguimientosGrid", action.result.seguimientos);
		    			Ext.WindowMgr.get("asgSeguimientoWindow").hide();
					}
    			},
    			failure: Asg.Form.failureProcedure
   			});
		},
		saveContacto: function(){
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			Ext.getCmp("asgContactoForm").getForm().submit({
    			url: Asg.constants.CONTEXT_PATH + "/contactos/save",
    			timeout: Asg.constants.TIMEOUT_SECONDS,
    			params: {
    				"asgContacto.asgVenta.asgVentaId": AsgSeguros.getAsgVentaId(),
    				"identifier": AsgSeguros.getAsgVentaId(),
    				type: "venta"
				},
    			success: function(form, action){
    				Asg.Message.alert(action.result.message);
					if(action.result.success){
						Asg.Grid.loadData("asgDetalleContactosGrid", action.result.contactos);
		    			Ext.WindowMgr.get("asgContactoWindow").hide();
					}
    			},
    			failure: Asg.Form.failureProcedure
   			});
		},
		addVenta: function(ctgTipoSeguros){
			var window = Ext.WindowMgr.get("asgVentaWindow");
			if(window){
				if(!window.isVisible()) window.show();
				return;
			}
			new Ext.Window({
				id: "asgVentaWindow",
				title: Asg.constants.APPLICATION_TITLE + " .::. AGREGAR VENTAS",
				modal: true,
				width: 810,
				height: 475,
	        	bodyStyle: "background: #DFE8F6",
	        	listeners: {
	        		show: function(){
	        			Ext.getCmp("asgVentaForm").getForm().reset();
	        		}
	        	},
	        	layout: "fit",
				items: {
		        	xtype: "form",
		        	id: "asgVentaForm",
		        	height: 205,
		        	border: false,
		        	bodyPadding: "5 5 5 5",
		        	layout: {
    	        		type: "table",
						columns: 6,
						tableAttrs: {
				            style: {width: "780px", "margin-top": "5px;"},
				            align: "center"
						}
    	        	},
    	        	defaults: Asg.Form.defaults({width: 255, colspan: 2}),
    	        	items: [
	        	        {xtype: "label", text: "Fecha:", cls: "x-form-item", colspan: 6},
	        	        {
	        	        	xtype: "datefield", 
	        	        	name: "asgVenta.asgVentaFechaCreacion",
	        	        	submitFormat: "Ymd",
	        	        	value: new Date(),
	        	        	readOnly: true,
	        	        	colspan: 6,
	        	        	width: 100
    	        		},
    	        		{xtype: "label", text: "Primer Nombre:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Segundo Nombre:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Tercer Nombre:", cls: "x-form-item"},
    	        		{
    	        			xtype: "textfield",
    	        			id: "asgVenta.PrimerNombre",
    	        			name: "asgVenta.asgVentaPrimerNombre",
    	        			allowBlank: false,
    	        			maxLength: 50
    	        		},{
    	        			xtype: "textfield",
    	        			id: "asgVentaSegundoNombre",
    	        			name: "asgVenta.asgVentaSegundoNombre",
    	        			maxLength: 50
    	        		},{
    	        			xtype: "textfield",
    	        			id: "asgVentaTercerNombre",
    	        			name: "asgVenta.asgVentaTercerNombre",
    	        			maxLength: 50
    	        		},
    	        		{xtype: "label", text: "Primer Apellido:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Segundo Apellido:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Apellido de Casada:", cls: "x-form-item"},
    	        		{
    	        			xtype: "textfield",
    	        			id: "asgVentaPrimerApellido",
    	        			name: "asgVenta.asgVentaPrimerApellido",
    	        			allowBlank: false,
    	        			maxLength: 30
    	        		},{
    	        			xtype: "textfield",
    	        			id: "asgVentaSegundoApellido",
    	        			name: "asgVenta.asgVentaSegundoApellido",
    	        			maxLength: 30
    	        		},{
    	        			xtype: "textfield",
    	        			id: "asgVentaApellidoCasada",
    	        			name: "asgVenta.asgVentaApellidoCasada",
    	        			maxLength: 30
    	        		},
    	        		{xtype: "label", text: "Tipo Seguro:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Tel\u00E9fono:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Celular:", cls: "x-form-item", colspan: 1, width: 130},
    	        		{xtype: "label", text: "Oficina:", cls: "x-form-item", colspan: 1, width: 125},
    	        		{
        	        		xtype: "combo",
        	        		name: "asgVenta.ctgTipoSeguro.ctgCatalogoId",
        	        		store: new Ext.data.SimpleStore({
        	        			data: ctgTipoSeguros || [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id",
        	        		allowBlank: false
    	        		},{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaTelefono1",
    	        			maxLength: 8,
    	        			vtype: "telefono"
    	        		},{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaTelefono2",
    	        			maxLength: 8,
    	        			vtype: "telefonoCelular",
    	        			width: 130,
    	        			colspan: 1
    	        		},{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaTelefono3",
    	        			maxLength: 8,
    	        			vtype: "telefono",
    	        			width: 115,
	        				colspan: 1
    	        		},
    	        		{xtype: "label", text: "Correo Electr\u00F3nico:", cls: "x-form-item", colspan: 6},
    	        		{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaCorreo",
    	        			vtype: "email",
    	        			maxLength: 250,
    	        			width: 775,
    	        			colspan: 6
    	        		},
    	        		{xtype: "label", text: "Asunto:", cls: "x-form-item", colspan: 6},
    	        		{
    	        			xtype: "textarea",
    	        			name: "asgVenta.asgVentaAsunto",
    	        			allowBlank: true,
    	        			height: 90,
    	        			width: 775,
    	        			colspan: 6,
    	        			allowBlank: false,
    	        			maxLength: 500
    	        		},
    	        		{xtype: "label", text: "Responsable:", cls: "x-form-item", colspan: 6},
    	        		{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaResponsable",
    	        			width: 775,
    	        			colspan: 6,
    	        			allowBlank: false,
    	        			maxLength: 200
    	        		},{
    	        			xtype: "hidden",
    	        			name: "ctgTipoPersonaCodigo",
    	        			value: 1
    	        		}
        	        ]
		        },
				buttons: [
		          {
		        	  text: "Guardar",
		        	  handler: function(){
		        		  AsgDetalleVenta.saveVenta(1);
		        	  }
		          },{
		        	  text: "Cerrar",
		        	  handler: function(){
		        		  Ext.WindowMgr.get("asgVentaWindow").hide();
		        	  }
		          }
	            ]
			}).show();
		},
		addVentaJuridica: function(ctgTipoSeguros){
			var window = Ext.WindowMgr.get("asgVentaJuridicaWindow");
			if(window){
				if(!window.isVisible()) window.show();
				return;
			}
			new Ext.Window({
				id: "asgVentaJuridicaWindow",
				title: Asg.constants.APPLICATION_TITLE + " .::. AGREGAR VENTAS",
				modal: true,
				width: 810,
				height: 425,
	        	bodyStyle: "background: #DFE8F6",
	        	listeners: {
	        		show: function(){
	        			Ext.getCmp("asgVentaJuridicaForm").getForm().reset();
	        		}
	        	},
	        	layout: "fit",
				items: {
		        	xtype: "form",
		        	id: "asgVentaJuridicaForm",
		        	height: 205,
		        	border: false,
		        	bodyPadding: "5 5 5 5",
		        	layout: {
    	        		type: "table",
						columns: 6,
						tableAttrs: {
				            style: {width: "780px", "margin-top": "5px;"},
				            align: "center"
						}
    	        	},
    	        	defaults: Asg.Form.defaults({width: 255, colspan: 2}),
    	        	items: [
	        	        {xtype: "label", text: "Fecha:", cls: "x-form-item", colspan: 6},
	        	        {
	        	        	xtype: "datefield", 
	        	        	name: "asgVenta.asgVentaFechaCreacion",
	        	        	submitFormat: "Ymd",
	        	        	value: new Date(),
	        	        	readOnly: true,
	        	        	colspan: 6,
	        	        	width: 100
    	        		},
    	        		{xtype: "label", text: "Raz\u00F3n Social:", cls: "x-form-item", colspan: 6},
    	        		{
    	        			xtype: "textfield",
    	        			id: "asgVenta.PrimerNombre",
    	        			name: "asgVenta.asgVentaPrimerNombre",
    	        			allowBlank: false,
    	        			colspan: 6,
    	        			width: 775,
    	        			maxLength: 200
    	        		},
    	        		{xtype: "label", text: "Tipo Seguro:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Tel\u00E9fono:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Celular:", cls: "x-form-item", colspan: 1, width: 130},
    	        		{xtype: "label", text: "Oficina:", cls: "x-form-item", colspan: 1, width: 125},
    	        		{
        	        		xtype: "combo",
        	        		name: "asgVenta.ctgTipoSeguro.ctgCatalogoId",
        	        		store: new Ext.data.SimpleStore({
        	        			data: ctgTipoSeguros || [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id",
        	        		allowBlank: false
    	        		},{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaTelefono1",
    	        			maxLength: 8,
    	        			vtype: "telefono"
    	        		},{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaTelefono2",
    	        			maxLength: 8,
    	        			vtype: "telefonoCelular",
    	        			width: 130,
    	        			colspan: 1
    	        		},{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaTelefono3",
    	        			maxLength: 8,
    	        			vtype: "telefono",
    	        			width: 115,
	        				colspan: 1
    	        		},
    	        		{xtype: "label", text: "Correo Electr\u00F3nico:", cls: "x-form-item", colspan: 6},
    	        		{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaCorreo",
    	        			vtype: "email",
    	        			maxLength: 250,
    	        			width: 775,
    	        			colspan: 6
    	        		},
    	        		{xtype: "label", text: "Asunto:", cls: "x-form-item", colspan: 6},
    	        		{
    	        			xtype: "textarea",
    	        			name: "asgVenta.asgVentaAsunto",
    	        			allowBlank: true,
    	        			height: 90,
    	        			width: 775,
    	        			colspan: 6,
    	        			allowBlank: false,
    	        			maxLength: 500
    	        		},
    	        		{xtype: "label", text: "Responsable:", cls: "x-form-item", colspan: 6},
    	        		{
    	        			xtype: "textfield",
    	        			name: "asgVenta.asgVentaResponsable",
    	        			width: 775,
    	        			colspan: 6,
    	        			allowBlank: false,
    	        			maxLength: 200
    	        		},{
    	        			xtype: "hidden",
    	        			name: "ctgTipoPersonaCodigo",
    	        			value: 2
    	        		}
        	        ]
		        },
				buttons: [
		          {
		        	  text: "Guardar",
		        	  handler: function(){
		        		  AsgDetalleVenta.saveVenta(2);
		        	  }
		          },{
		        	  text: "Cerrar",
		        	  handler: function(){
		        		  Ext.WindowMgr.get("asgVentaJuridicaWindow").hide();
		        	  }
		          }
	            ]
			}).show();
		},
		addSeguimiento: function(){
			var row = Asg.Grid.getSelectedRow("asgDetalleVentasGrid");
			if(!row){
				Asg.Message.alertInvalid("Debe seleccionar la venta a la que desea agregarle un seguimiento");
				return;
			}else if(row.get("asgVentaFinalizado") == "1"){
				Asg.Message.alertInvalid("Venta finalizada");
				return;
			}
			var window = Ext.WindowMgr.get("asgSeguimientoWindow");
			if(window){
				if(!window.isVisible()) window.show();
				return;
			}
			new Ext.Window({
				id: "asgSeguimientoWindow",
				title: Asg.constants.APPLICATION_TITLE + " .::. AGREGAR SEGUIMIENTOS",
				modal: true,
				width: 500,
				height: 300,
	        	bodyStyle: "background: #DFE8F6",
	        	listeners: {
	        		show: function(){
	        			var asgVenta = Asg.Grid.getSelectedRow("asgDetalleVentasGrid");
	        			Ext.getCmp("asgSeguimientoForm").getForm().reset();
	        			Asg.Utils.setValue("asgSeguimientoCliente", asgVenta.get("asgVentaNombreCompleto"));
	        			Asg.Utils.setValue("asgSeguimientoVentaNumero", asgVenta.get("asgVentaNumero"));
	        			var asgContactos = [];
	        			Ext.each(Ext.getCmp("asgDetalleContactosGrid").getStore().getRange(), function(record){
	        				asgContactos.push([
			                   record.get("asgContacto.asgContactoId"),
			                   record.get("asgContacto.asgContactoNombre") + " - " +
			                   record.get("ctgTipoContactoNombre")
		                   ]);
	        			});
	        			Asg.Combo.loadData("asgSeguimientoContacto", asgContactos);
	        		}
	        	},
	        	layout: "fit",
				items: {
		        	xtype: "form",
		        	id: "asgSeguimientoForm",
		        	height: 205,
		        	border: false,
		        	bodyPadding: "0 5 5 5",
		        	layout: {
    	        		type: "table",
						columns: 2,
						tableAttrs: {
				            style: {width: "420px"},
				            align: "center"
						}
    	        	},
    	        	defaults: Asg.Form.defaults({width: 410, allowBlank: false, colspan: 2, labelAlign: "top"}),
    	        	items: [
	        	        {
	        	        	xtype: "textfield", 
	        	        	fieldLabel: "No. Venta",
	        	        	id: "asgSeguimientoVentaNumero",
	        	        	disabled: true,
	        	        	width: 200, 
	        	        	colspan: 1
    	        		},{
	        	        	xtype: "datefield", 
	        	        	fieldLabel: "Proximo Seguimiento",
	        	        	name: "asgSeguimiento.asgSeguimientoFechaSiguiente",
	        	        	submitFormat: "Ymd",
	        	        	value: new Date(),
	        	        	minValue: new Date(),
	        	        	labelWidth: 200,
	        	        	width: 200, 
	        	        	colspan: 1
    	        		},{
    	        			xtype: "textfield",
    	        			id: "asgSeguimientoCliente",
    	        			fieldLabel: "Cliente",
    	        			disabled: true
    	        		},{
    	        			xtype: "textarea",
    	        			fieldLabel: "Asunto",
    	        			name: "asgSeguimiento.asgSeguimientoDescripcion",
    	        			allowBlank: true,
    	        			height: 90,
    	        			maxLength: 500
    	        		},{
        	        		xtype: "combo",
        	        		id: "asgSeguimientoContacto",
        	        		name: "asgSeguimiento.asgContacto.asgContactoId",
        	        		fieldLabel: "Tipo de Contacto",
        	        		store: new Ext.data.SimpleStore({
        	        			data: [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id"
    	        		}
        	        ]
		        },
				buttons: [
		          {
		        	  text: "Guardar",
		        	  handler: function(){
		        		  AsgDetalleVenta.saveSeguimiento();
		        	  }
		          },{
		        	  text: "Cerrar",
		        	  handler: function(){
		        		  Ext.WindowMgr.get("asgSeguimientoWindow").hide();
		        	  }
		          }
	            ]
			}).show();
		},
		addContacto: function(ctgTipoContactos){
			var row = Asg.Grid.getSelectedRow("asgDetalleVentasGrid");
			if(!row){
				Asg.Message.alertInvalid("Debe seleccionar la venta a la que desea agregarle un contacto");
				return;
			}else if(row.get("asgVentaFinalizado") == "1"){
				Asg.Message.alertInvalid("Venta finalizada");
				return;
			}
			var window = Ext.WindowMgr.get("asgContactoWindow");
			if(window){
				if(!window.isVisible()) window.show();
				return;
			}
			new Ext.Window({
				id: "asgContactoWindow",
				title: Asg.constants.APPLICATION_TITLE + " .::. AGREGAR CONTACTOS",
				modal: true,
				width: 500,
				height: 260,
	        	bodyStyle: "background: #DFE8F6",
	        	listeners: {
	        		show: function(){
	        			Ext.getCmp("asgContactoForm").getForm().reset();
	        		}
	        	},
	        	layout: "fit",
				items: {
		        	xtype: "form",
		        	id: "asgContactoForm",
		        	height: 205,
		        	border: false,
		        	bodyPadding: "5 5 5 5",
		        	layout: {
    	        		type: "table",
						columns: 4,
						tableAttrs: {
				            style: {width: "420px"},
				            align: "center"
						}
    	        	},
    	        	defaults: Asg.Form.defaults({width: 410, allowBlank: false, colspan: 2, labelAlign: "top"}),
    	        	items: [
	        	        {
        	        		xtype: "combo",
        	        		name: "asgContacto.ctgTipoContacto.ctgCatalogoId",
        	        		fieldLabel: "Tipo de Contacto",
        	        		store: new Ext.data.SimpleStore({
        	        			data: ctgTipoContactos || [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id",
        	        		colspan: 4
    	        		},{
    	        			xtype: "textfield",
    	        			fieldLabel: "Nombre del Contacto",
    	        			name: "asgContacto.asgContactoNombre",
    	        			maxLength: 250,
        	        		colspan: 4
    	        		},{
    	        			xtype: "textfield",
    	        			fieldLabel: "Tel\u00E9fono del Contacto",
    	        			name: "asgContacto.asgContactoTelefono",
    	        			maxLength: 8,
    	        			vtype: "telefono", 
    	        			width: 200
    	        		},{
    	        			xtype: "textfield",
    	        			fieldLabel: "Tel\u00E9fono",
    	        			name: "asgContacto.asgContactoTelefono2",
    	        			maxLength: 8,
    	        			vtype: "telefono", 
    	        			colspan: 1,
    	        			allowBlank: true,
    	        			width: 140
    	        		},{
    	        			xtype: "textfield",
    	        			fieldLabel: "Ext.",
    	        			name: "asgContacto.asgContactoTelefonoExtension",
    	        			maxLength: 6,
    	        			maskReg: /[0-9]/,
    	        			colspan: 1,
    	        			allowBlank: true,
    	        			width: 50
    	        		},{
    	        			xtype: "textfield",
    	        			fieldLabel: "Correo Electr\u00F3nico del Contacto",
    	        			name: "asgContacto.asgContactoCorreo",
    	        			maxLength: 500,
    	        			vtype: "email", 
    	        			colspan: 1,
    	        			allowBlank: true,
    	        			colspan: 4
    	        		}
        	        ]
		        },
				buttons: [
		          {
		        	  text: "Guardar",
		        	  handler: function(){
		        		  AsgDetalleVenta.saveContacto();
		        	  }
		          },{
		        	  text: "Cerrar",
		        	  handler: function(){
		        		  Ext.WindowMgr.get("asgContactoWindow").hide();
		        	  }
		          }
	            ]
			}).show();
		},
		getRowBodyContents: function(data) {
            return rowBodyTpl.applyTemplate(data);
        },
		loadVentas: function(){
			Asg.Message.progress("Cargando Informaci\u00F3n...");
			Ext.Ajax.request({
    			timeout: Asg.constants.TIMEOUT_SECONDS,
  			    url: Asg.constants.CONTEXT_PATH + "/ventas/findByAsgPolizaId",
  			    params: {
  			    	asgPolizaId: AsgSeguros.getAsgPolizaId()
  			    },
  			    callback: function(options, success, response){
  			    	Ext.Msg.hide();
  			    	if(success){
  			    		var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
  			    		if(jsonObject && jsonObject.success){
  			    			Asg.Grid.loadData("asgDetalleVentasGrid", jsonObject.ventas);
  			    		}else{
  			    			Asg.Message.alertInvalid(jsonObject ? (jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE) : Asg.constants.DEFAULT_ERROR_MESSAGE);
  			    		}
  			    	}
  			    }
  			});
		},
		loadSeguimientos: function(){
			Asg.Message.progress("Cargando Informaci\u00F3n...");
			Ext.Ajax.request({
    			timeout: Asg.constants.TIMEOUT_SECONDS,
  			    url: Asg.constants.CONTEXT_PATH + "/ventas/findByType",
  			    params: {
  			    	asgVentaId: AsgSeguros.getAsgVentaId()
  			    },
  			    callback: function(options, success, response){
  			    	Ext.Msg.hide();
  			    	if(success){
  			    		var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
  			    		if(jsonObject && jsonObject.success){
  			    			Asg.Grid.loadData("asgDetalleSeguimientosGrid", jsonObject.seguimientos);
  			    			Asg.Grid.loadData("asgDetalleContactosGrid", jsonObject.contactos);
  			    		}else{
  			    			Asg.Message.alertInvalid(jsonObject ? (jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE) : Asg.constants.DEFAULT_ERROR_MESSAGE);
  			    		}
  			    	}
  			    }
  			});
		},
		confirmDeleteSeguimiento: function(){
			var row = Asg.Grid.getSelectedRow("asgDetalleSeguimientosGrid"); 
			if(!row){
				Asg.Message.alertInvalid("Debe seleccionar el seguimiento a eliminar");
				return;
			}
			Asg.Message.confirmDelete(AsgDetalleVenta.deleteSeguimiento);
		},
		deleteSeguimiento: function(){
			var row = Asg.Grid.getSelectedRow("asgDetalleSeguimientosGrid");
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			Ext.Ajax.request({
    			timeout: Asg.constants.TIMEOUT_SECONDS,
  			    url: Asg.constants.CONTEXT_PATH + "/seguimientos/deleteSeguimiento",
  			    params: {
  			    	type: "venta",
  			    	asgSeguimientoId: row.get("asgSeguimientoId"),
  			    	identifier: AsgSeguros.getAsgVentaId()
  			    },
  			    callback: function(options, success, response){
  			    	Ext.Msg.hide();
  			    	if(success){
  			    		var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
  			    		if(jsonObject && jsonObject.success){
  			    			Asg.Message.alert(jsonObject.message);
  			    			Asg.Grid.loadData("asgDetalleSeguimientosGrid", jsonObject.seguimientos);
  			    		}else{
  			    			Asg.Message.alertInvalid(jsonObject ? (jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE) : Asg.constants.DEFAULT_ERROR_MESSAGE);
  			    		}
  			    	}
  			    }
  			});
		},
		confirmDeleteContacto: function(){
			var row = Asg.Grid.getSelectedRow("asgDetalleContactosGrid"); 
			if(!row){
				Asg.Message.alertInvalid("Debe seleccionar el contacto a eliminar");
				return;
			}
			Asg.Message.confirmDelete(AsgDetalleVenta.deleteContacto, null, 
					"Se eliminara tambien la informacion asociada al contacto, tales como: <br />* Seguimientos");
		},
		deleteContacto: function(){
			var row = Asg.Grid.getSelectedRow("asgDetalleContactosGrid");
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			Ext.Ajax.request({
    			timeout: Asg.constants.TIMEOUT_SECONDS,
  			    url: Asg.constants.CONTEXT_PATH + "/contactos/deleteContacto",
  			    params: {
  			    	type: "venta",
  			    	asgContactoId: row.get("asgContacto.asgContactoId"),
  			    	identifier: AsgSeguros.getAsgVentaId()
  			    },
  			    callback: function(options, success, response){
  			    	Ext.Msg.hide();
  			    	if(success){
  			    		var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
  			    		if(jsonObject && jsonObject.success){
  			    			Asg.Message.alert(jsonObject.message);
  			    			AsgDetalleVenta.loadSeguimientos();
  			    		}else{
  			    			Asg.Message.alertInvalid(jsonObject ? (jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE) : Asg.constants.DEFAULT_ERROR_MESSAGE);
  			    		}
  			    	}
  			    }
  			});
		},
		confirmDeleteVenta: function(){
			var row = Asg.Grid.getSelectedRow("asgDetalleVentasGrid"); 
			if(!row){
				Asg.Message.alertInvalid("Debe seleccionar el Venta a eliminar");
				return;
			}
			Asg.Message.confirmDelete(AsgDetalleVenta.deleteVenta, null, 
					"Se eliminara tambien la informacion asociada al venta, tales como: <br />*Contactos <br />* Seguimientos");
		},
		deleteVenta: function(){
			var row = Asg.Grid.getSelectedRow("asgDetalleVentasGrid");
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			Ext.Ajax.request({
    			timeout: Asg.constants.TIMEOUT_SECONDS,
  			    url: Asg.constants.CONTEXT_PATH + "/ventas/deleteVenta",
  			    params: {
  			    	asgVentaId: row.get("asgVentaId")
  			    },
  			    callback: function(options, success, response){
  			    	Ext.Msg.hide();
  			    	if(success){
  			    		var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
  			    		if(jsonObject && jsonObject.success){
  			    			Asg.Message.alert(jsonObject.message);
  			    			Ext.StoreMgr.get("asgDetalleVentaStore").currentPage = 1;
  			    			Ext.StoreMgr.get("asgDetalleVentaStore").load({params:{restart: true}});
     	        		    AsgSeguros.setAsgClienteId(null);
     	        		    AsgSeguros.setAsgPolizaId(null);
     	        		    Asg.Grid.loadData("asgDetalleSeguimientosGrid", []);
    					    Asg.Grid.loadData("asgDetalleContactosGrid", []);
  			    		}else{
  			    			Asg.Message.alertInvalid(jsonObject ? (jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE) : Asg.constants.DEFAULT_ERROR_MESSAGE);
  			    		}
  			    	}
  			    }
  			});
		},
		initConfig: function(config){
			config = config || {};
			Ext.define("asgDetalleVentaModel", {
			    extend: "Ext.data.Model",
		        fields: [
		             "asgVentaId", "asgVentaNumero", "asgVentaNombreCompleto", 
		             "asgVentaResponsable", "asgVentaAsunto", "asgVentaFecha", "asgVentaFinalizado",
		             "asgVentaFechaFinalizacion", "asgVentaTelefono1", "asgVentaTelefono2", "asgVentaTelefono3",
		             "asgVentaCorreo", "ctgTipoSeguroId", "ctgTipoSeguroNombre", "ctgTipoPersonaNombre" 
		        ]
			});
			var asgDetalleVentaStore = Ext.create("Ext.data.Store", {
				id: "asgDetalleVentaStore",
				autoLoad: true,
				pageSize: Asg.constants.PAGE_SIZE,
				model: "asgDetalleVentaModel",
				proxy: {
			        type: "ajax",
			        url: Asg.constants.CONTEXT_PATH + "/ventas/findAllBy",
			        reader: {
			        	type: "array",
			        	root: "list",
			        	totalProperty: "totalResult"
	        		}
			    },
			    groupers: [{property: "ctgTipoPersonaNombre"}],
			    listeners: {
			    	beforeload: function(store, operation, options){
			    		if(!operation) operation = {};
			    		if(!operation.params) operation.params = {};
			    		var form = Ext.getCmp("asgDetalleAbonoForm").getForm();
			    		if(!form.isValid()){
			    			Asg.Message.alertInvalidFields();
			    			return false;
			    		}
			    		var values = form.getValues();
			    		for(value in values){
			    			operation.params["asgSeguroForm." + value] = values[value];
			    		}
			    		if(operation.params.restart){
			    			operation.start = 0;
			    			operation.page = 1;
			    		}
		    			Asg.Grid.loadData("asgDetalleSeguimientosGrid", []);
			    	}
			    	
			    }
			});
			return {
				menu: [
	                "->",
	                Viewport.getMenuHome()
                ],
				items: {
					border: false,
					bodyStyle: "background: #DFE8F6",
					flex: 1,
					layout: {
						type: "vbox",
						align : "stretch",
						pack  : "start"
					},
					items:[
				       {
				        	height: 300,
				        	border: false,
				        	bodyStyle: "background: #DFE8F6",
				        	layout: {
								type: "vbox",
								align : "stretch",
								pack  : "start"
							},
							items: [
								{
						        	xtype: "form",
						        	id: "asgDetalleAbonoForm",
						        	height: 75,
						        	bodyStyle: "background: #DFE8F6",
						        	layout: "fit",
						        	border: false,
						        	margins: "0 0 5 0",
									items: {
										xtype: "fieldset",
										title: "PARAMETROS DE BUSQUEDA",
										style: "background: #FFFFFF;",
										layout: {
				        	        		type: "table",
											columns: 4,
											tableAttrs: {
									            style: {width: "500px"},
									            align: "center"
											}
				        	        	},
				        	        	defaults: Asg.Form.defaults({width: 250, labelAlign: "top", style: "margin-left: 10px"}),
				        	        	items: [
				    	        	        {
				    	        	        	xtype: "datefield",
				    	        	        	id: "asgFechaInicio1",
				    	        	        	name: "asgFechaInicio1",
				    	        	        	fieldLabel: "Fecha Creaci\u00F3n",
				    	        	        	width: 110,
				    	        	        	submitFormat: "Ymd",
				    	        	        	colspan: 1
				    	        	        },{
				    	        	        	xtype: "datefield",
				    	        	        	id: "asgFechaInicio2",
				    	        	        	name: "asgFechaInicio2",
				    	        	        	fieldLabel: " ",
				    	        	        	labelSeparator: "&nbsp;",
				    	        	        	width: 105,
				    	        	        	submitFormat: "Ymd",
				    	        	        	colspan: 1
				    	        	        },{
				    	        	        	xtype: "textfield",
				    	        	        	id: "asgClienteNombreCompleto",
				    	        	        	name: "asgClienteNombreCompleto",
				    	        	        	fieldLabel: "Nombre del Cliente",
				    	        	        	width: 325
				    	        	        },{
				    	        	        	xtype: "combo",
				    	        	        	id: "asgEstados",
				    	        	        	name: "asgFinalizado",
				    	        	        	fieldLabel: "Estado",
		        	        	        		store: new Ext.data.SimpleStore({
		        	        	        			data: Asg.Combo.status(),
		        	        	        			fields: ["id", "value"]
		        	        	        		}),
		        	        	        		displayField: "value",
		        	        	        		valueField: "id",
		        	        	        		value: "0",
				    	        	        	width: 225
				    	        	        }
					        	        ]
									}
						        },{
									xtype: "grid",
									id: "asgDetalleVentasGrid",
									margins: "0 0 5 0",
									flex: 1,
									frame: true,
									dockedItems: [
			                           {
			                        	   xtype: "toolbar",
			                        	   dock: "top",
			                        	   items: [
										       "->",
										       {
			                    	        	   text: "Buscar", 
			                    	        	   iconCls: Asg.constants.SEARCH_ICON,
			                    	        	   handler: function(){
			                    	        		   asgDetalleVentaStore.currentPage = 1;
			                    	        		   asgDetalleVentaStore.load({params:{restart: true}});
			                    	        		   AsgSeguros.setAsgClienteId(null);
			                    	        		   AsgSeguros.setAsgPolizaId(null);
			                    	        		   Asg.Grid.loadData("asgDetalleSeguimientosGrid", []);
			                   						   Asg.Grid.loadData("asgDetalleContactosGrid", []);
			                    	        	   }
			                	        	   },{
			                    	        	   text: "Borrar Filtros", 
			                    	        	   iconCls: Asg.constants.CANCEL_ICON,
			                    	        	   handler: function(){
			                    	        		   Ext.getCmp("asgDetalleAbonoForm").getForm().reset();
			                    	        	   }
			                	        	   }, "-", "-",
										       {
						    			        	text: "Agregar", 
						    			        	iconCls: Asg.constants.ADD_ICON,
						    			        	hidden: config.isReadOnly,
						    			        	menu: [
					    			        	       {
					    			        	    	   text: "Persona Natural",
						    			        	       handler: function(){
						    			        	    	   AsgDetalleVenta.addVenta(config.ctgTipoSeguros || []);
						    			        	       }
										       		   },{
					    			        	    	   text: "Persona Juridica",
						    			        	       handler: function(){
						    			        	    	   AsgDetalleVenta.addVentaJuridica(config.ctgTipoSeguros || []);
						    			        	       }
										       		   }
				    			        	        ]
										       },{
					        	        			text: "Eliminar",
					        	        			iconCls: Asg.constants.DELETE_ICON,
					        	        			hidden: !config.allowDelete,
					        	        			handler: AsgDetalleVenta.confirmDeleteVenta
		   		    	        			   },{
										    	   text: "Finalizar", 
										    	   iconCls: Asg.constants.ACCEPT_ICON,
										    	   hidden: config.isReadOnly,
										    	   handler: AsgDetalleVenta.confirmFinalizacion
										       }
									       ]
			                           },{
			                        	   xtype: "pagingtoolbar",
			                        	   store: asgDetalleVentaStore,
			                        	   dock: "bottom",
			                        	   displayInfo: true
						               }
							        ],
									store: asgDetalleVentaStore,
									columns: [
							          	{dataIndex: "asgVentaFinalizado", width: 30, renderer: AsgDetalleVenta.rendererEstado},
										{header: "Tipo Seguro", dataIndex: "ctgTipoSeguroNombre", width: 150},
										{header: "Cliente", dataIndex: "asgVentaNombreCompleto", minWidth: 250, flex: 1},
								        {header: "Responsable", dataIndex: "asgVentaResponsable", minWidth: 150, flex: 1},
								        {header: "Fecha", dataIndex: "asgVentaFecha", width: 100, renderer: "webFormatDateYmd_d_m_Y"},
								        {header: "Tel\u00E9fono", dataIndex: "asgVentaTelefono1", width: 150},
								        {header: "Celular", dataIndex: "asgVentaTelefono2", width: 150},
								        {header: "Oficina", dataIndex: "asgVentaTelefono3", width: 150},
								        {header: "Correo", dataIndex: "asgVentaCorreo", width: 250}
								    ],
								    selModel:{
				        	            listeners: {
				        	            	selectionchange: function(selectionModel, rows){
				        	            		if(rows && rows.length > 0){
				        	            			AsgSeguros.setAsgVentaId(rows[0].get("asgVentaId"));
				        	            			AsgDetalleVenta.loadSeguimientos();
				        	            		}
				        	            	}
				        	            }
			        	            },
								    features: [
								       {
								    	   ftype: 'rowbody',
								    	   getAdditionalData: Asg.Grid.getAdditionalData,
								    	   getRowBodyContents: AsgDetalleVenta.getRowBodyContents
								       },{
							        	   ftype: "grouping",
							        	   enableNoGroups: false,
							        	   groupHeaderTpl: 'PERSONA {name} -> {rows.length} Registro{[values.rows.length > 1 ? "s" : ""]}'
							           }
								    ]
								}
					        ]
				        },
				        {
				        	flex: 1,
				        	minWidth: 500,
				        	border: false,
				        	bodyStyle: "background: #DFE8F6",
				        	layout: {
								type: "hbox",
								align : "stretch",
								pack  : "start"
							},
							items: [
								{
						        	flex: 1,
						        	minWidth: 450,
						        	border: false,
						        	bodyStyle: "background: #DFE8F6",
						        	layout: {
										type: "hbox",
										align : "stretch",
										pack  : "start"
									},
									items: [
										{
											xtype: "grid",
											id: "asgDetalleContactosGrid",
											title: "Contactos",
											margins: "0 5 5 0",
											flex: 1,
											frame: true,
											tbar: [
												"->",
												{
													text: "Agregar", 
													iconCls: Asg.constants.ADD_ICON,
													hidden: config.isReadOnly,
													handler: function(){
														AsgDetalleVenta.addContacto(config.ctgTipoContactos);
													}
												},{
					        	        			text: "Eliminar",
					        	        			iconCls: Asg.constants.DELETE_ICON,
					        	        			hidden: !config.allowDelete,
					        	        			handler: AsgDetalleVenta.confirmDeleteContacto
		   		    	        			   }
									        ],
											store: new Ext.data.SimpleStore({
												data: [],
										        fields: [
										             "asgContacto.asgContactoId", "asgContacto.asgContactoNombre", "asgContacto.asgContactoTelefono",
										             "asgContacto.asgContactoTelefono2", "asgContacto.asgContactoTelefonoExtension",
										             "asgContacto.asgContactoCorreo", "asgContacto.ctgTipoContacto.ctgCatalogoId", 
										             "ctgTipoContactoNombre"
										        ]
											}),
											columns: [
									            {header: "Tipo", dataIndex: "ctgTipoContactoNombre", width: 160},
										        {header: "Nombre", dataIndex: "asgContacto.asgContactoNombre", minWidth: 185, flex: 1},
										        {header: "Tel\u00E9fono", dataIndex: "asgContacto.asgContactoTelefono", width: 65},
										        {header: "Tel\u00E9fono", dataIndex: "asgContacto.asgContactoTelefono2", width: 65},
										        {header: "Ext.", dataIndex: "asgContacto.asgContactoTelefonoExtension", width: 65},
										        {header: "Correo Electr\u00F3nico", dataIndex: "asgContacto.asgContactoCorreo", width: 250, renderer: "mailTo"}
										    ]
										},{
											xtype: "grid",
											id: "asgDetalleSeguimientosGrid",
											title: "Seguimientos",
											margins: "0 0 5 0",
											flex: 1,
											frame: true,
											tbar: [
												"->",
												{
													text: "Agregar", 
													iconCls: Asg.constants.ADD_ICON,
													hidden: config.isReadOnly,
													handler: function(){
														AsgDetalleVenta.addSeguimiento();
													}
												},{
					        	        			text: "Eliminar",
					        	        			iconCls: Asg.constants.DELETE_ICON,
					        	        			hidden: !config.allowDelete,
					        	        			handler: AsgDetalleVenta.confirmDeleteSeguimiento
		   		    	        			   }
									        ],
											store: new Ext.data.SimpleStore({
												data: [],
										        fields: [
										             "asgSeguimientoId", "asgSeguimientoFecha", "asgSeguimientoFechaSiguiente", 
										             "asgContactoNombre", "ctgTipoContactoNombre", "asgSeguimientoDescripcion"
										        ],
										        sorters: [{property: "asgSeguimientoId", direction: "DESC"}]
											}),
											columns: [
										        {header: "Tipo", dataIndex: "ctgTipoContactoNombre", width: 140},
										        {header: "Responsable", dataIndex: "asgContactoNombre", minWidth: 150, flex: 1},
										        {header: "Proximo Seguimiento", dataIndex: "asgSeguimientoFechaSiguiente", width: 115, align: "right", renderer: "webFormatDateYmd_d_m_Y", style: "color: darkred"},
										        {header: "Fecha Ingreso", dataIndex: "asgSeguimientoFecha", width: 85, renderer: "webFormatDateYmd_d_m_Y"}
										    ],
										    features: [
										       {
										    	   ftype: 'rowbody',
										    	   getAdditionalData: Asg.Grid.getAdditionalData,
										    	   getRowBodyContents: AsgDetalleVenta.getRowBodyContents
										       }
										    ]
										}
							        ]
								}
					        ]
				        }
			        ]
				}
			};
		}
	};
}();